package com.lang8.util.dict;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.lang8.util.database.ConnectionUtil;

public class LanguageDict {
	private static LanguageDict instance = new LanguageDict();
	private static boolean isInit = false;
	private List<String[]> en_USList = new ArrayList<String[]>();
	private List<String[]> zh_CNList = new ArrayList<String[]>();
	private Map<String, List<String[]>> dispLangMap = new HashMap<String, List<String[]>>();
	private LanguageDict(){}
	private void init() {
		dispLangMap.put("en_US", en_USList);
		dispLangMap.put("zh_CN", zh_CNList);
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			try {
				conn = ConnectionUtil.getConnection();
				String sql = "SELECT LANG_KEY, DISP_LANG, LANG_VALUE FROM lang_info ORDER BY LANG_INFO_ID";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				while (rs.next()) {
					String langKey = rs.getString(1);
					String dispLang = rs.getString(2);
					String langValue = rs.getString(3);
					dispLangMap.get(dispLang).add(new String[]{langKey, langValue});
				}
			} catch (Exception e) {
				throw e;
			} finally {
				ConnectionUtil.releaseConnection(rs, pstmt, conn);
			}
			Collections.sort(zh_CNList, new Comparator<String[]>() {
				@Override
				public int compare(String[] o1, String[] o2) {
					//Pinyin order
					return Collator.getInstance(Locale.CHINESE).compare(o1[1], o2[1]);
				}
			});
			isInit = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//APIs
	
	public static LanguageDict getInstance(){
		if (!isInit) {
			synchronized (LanguageDict.class) {
				if (!isInit) {
					instance.init();
				}
			}
		}
		return instance;
	}
	public static List<String[]> getLanguageList(String dispLang){
		LanguageDict instance = getInstance();
		if (instance.dispLangMap.containsKey(dispLang)) {
			return instance.dispLangMap.get(dispLang);
		} else {
			return instance.en_USList;
		}
	}
}
